import * as fs from "fs";
import * as path from "path";
import { ConfigComponentInvoke } from "../../../Core/Module/Config/ConfigComponent";
import { EventSystem } from "../../../Core/Module/EventSystem/EventSystem";
import { AInvokeHandler1 } from "../../../Core/Module/EventSystem/IInvoke";
import { Options } from "../../../Core/Module/Options/Options";
import { ConfigAttribute, GetTypeOf, InvokeAttribute } from "../../../Decorator/Decorator";
import { Dictionary } from "../../Share/Lib/Dictionary";
import { IMerge } from "../../../Core/Module/Config/IMerge";

@InvokeAttribute(0, ConfigComponentInvoke.GetAllConfig)
export class GetAllConfig extends AInvokeHandler1<ConfigComponentInvoke.GetAllConfig, Dictionary<string, any>> {

    Handle(args: ConfigComponentInvoke.GetAllConfig): Dictionary<string, any> {
        const output = new Dictionary<string, any>();

        // console.log(`GetAllConfig.Handle`);
        // console.log(args);

        const RootPath = path.join(__dirname, "../../../../../");

        let startConfigs = [
            "ServerInfoConfigCategory",
            "StartMachineConfigCategory",
            "StartProcessConfigCategory",
            "StartSceneConfigCategory",
            "StartZoneConfigCategory",
        ];
        const configTypes = EventSystem.Instance.GetTypes(GetTypeOf(ConfigAttribute));
        for (const type in configTypes) {
            const clazz = configTypes[type];
            const configCategoryType = GetTypeOf(clazz);
            const configType = configCategoryType.replace("Category", "");
            let configFilePath = "";
            if (startConfigs.indexOf(configCategoryType) != -1) {
                configFilePath = `Config/Excel/${Options.Instance.StartConfig}/${configType}.txt`;
            } else {
                configFilePath = `Config/Excel/${configType}.txt`;
            }
            const JsonPath = path.join(RootPath, configFilePath);
            const fileContent = fs.readFileSync(JsonPath);
            const jsonObject = JSON.parse(fileContent.toString());

            let singleton = new clazz() as IMerge;
            singleton.MergeJson(jsonObject);

            // console.log(fileContent.toString());

            output[configCategoryType] = singleton;
        }

        // console.log(output);

        return output;
    }

}